﻿using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utity;

namespace PythonStart
{
    public class ExecutePython
    {


        public ParamterSet Run(string mainFile,ParamterSet pset,List<string> lstOutputOption)
        {
            try
            {
                ScriptEngine engine = IronPython.Hosting.Python.CreateEngine();
                ScriptScope scope = engine.CreateScope();
                if (pset.HasKeys())
                {
                    foreach (string key in pset.GetValues().Keys)
                    {
                        scope.SetVariable(key, pset.GetValue(key));
                    }
                }
                ScriptSource source = engine.CreateScriptSourceFromFile(Path.Combine(System.Environment.CurrentDirectory, "pythonLib", mainFile + (mainFile.EndsWith(".py") ? "" : ".py")));
                source.Execute(scope);
                List<string> lstVarNames = new List<string>(scope.GetVariableNames());
                ParamterSet output = new ParamterSet();
                foreach (string varName in lstVarNames)
                {
                    if (varName.StartsWith("__") && varName.EndsWith("__"))
                        continue;
                    if (lstOutputOption != null && lstOutputOption.Count > 0)
                    {
                        if (lstOutputOption.IndexOf(varName) > -1)
                        {
                            output.SetValue(varName, scope.GetVariable(varName));
                        }
                    }
                    else if (varName.StartsWith("R_") || varName.StartsWith("RETURN_") || varName.StartsWith("RTN_"))
                    {
                        output.SetValue(varName, scope.GetVariable(varName));
                    }
                }
                
                return output;
            }
            catch (SelfException appEx)
            {
                return new ParamterSet().SetValueChain("RETURN_CODE", 999).SetValueChain("RETURN_MESSAGE", "Python Run异常:" + appEx.Message);
            }
            catch (Exception ex)
            {
                return new ParamterSet().SetValueChain("RETURN_CODE", 99).SetValueChain("RETURN_MESSAGE", "系统异常:" + ex.Message);
            }
        }

    }
}
